//
//  HOMediaViewController.m
//  WeiDu
//
//  Created by foguo-mac-1 on 13/12/2017.
//  Copyright © 2017 WeiDu. All rights reserved.
//

#import "HOMediaViewController.h"
#import "HOUtils.h"
#import "HODefaultImage.h"
#import "HOTakePhotoMgr.h"
#import "HORecordActiveView.h"
#import "VoiceConverter.h"
#import "HORecordView.h"
#import "GTMBase64.h"
#import "HOVoiceDownloader.h"
#import "HOConstants.h"
#import "HOBigImageViewController.h"

@implementation HOMediaViewController
@synthesize recordActiveView;
@synthesize totalTime;
@synthesize singleImgWidth;
@synthesize voiceFileURL;
@synthesize recordView;
@synthesize isRecordModal;

- (void)initMediaView
{
	[self initRecordActiveViewWithIsRecordModal:YES];
	[self initImageUploadView];
	[self initAuditionView];
}

- (void)initMediaViewNoRecord
{
	[self initRecordActiveViewWithIsRecordModal:NO];
	[self initImageUploadView];
	self.uploadImgView.needDisplayRemoveButton = NO;
	[self.uploadImgView hideUploadButton];

}

- (void)initMediaViewOnlyImageDiaplay
{
	[self initImageUploadView];
	self.uploadImgView.needDisplayRemoveButton = YES;
}

- (void)initRecordActiveViewWithIsRecordModal:(BOOL)isRecordModal
{
	self.isRecordModal = isRecordModal;
	self.recordActiveView = [[[HORecordActiveView alloc]
							  initWithFrame:CGRectMake(self.view.frame.size.width/2 - 70,
													   [UIScreen mainScreen].bounds.size.height/2 - 120,
													   140,
													   140)] autorelease];
	self.recordActiveView.hidden = YES;
	self.recordActiveView.delegate = self;
	self.recordActiveView.layer.borderWidth = 1;
	[self.view addSubview:self.recordActiveView];
	
	self.recordView = [[[HORecordView alloc] initWithFrame:CGRectMake(0,
																	  0,
																	  self.view.frame.size.width,
																	  50 + 128) isRecordModal:isRecordModal] autorelease];
	self.recordActiveView.textLbl = self.recordView.textLbl;
	self.recordView.delegate = self.recordActiveView;
	self.recordView.downloadDelegate = self;
}

- (void)initImageUploadView
{
	
	CGFloat screenWidth = [HOUtils getScreenWidth];
	self.singleImgWidth = (screenWidth - 4 * HO_HORIZONAL_PADDING) / 3;
	
	self.takePhotoMgr = [[[HOTakePhotoMgr alloc] init] autorelease];
	self.takePhotoMgr.delegate = self;
	self.takePhotoMgr.viewController = self;
	self.uploadImgView = [[[HOUploadImageView alloc]
						   initWithFrame:CGRectMake(0,
													134,
													self.view.frame.size.width,
													self.singleImgWidth)] autorelease];
	self.uploadImgView.delegate = self;
	self.uploadImgView.needDisplayRemoveButton = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForQuickTakePhotoRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *HOTakePhotoTableViewCellIdentifier = @"HOTakePhotoTableViewCellIdentifier";
	HOTableViewCell *cell = (HOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOTakePhotoTableViewCellIdentifier];
	if(cell == nil)
	{
		cell = [[[HOTableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier: HOTakePhotoTableViewCellIdentifier] autorelease];
	}
	//	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
	cell.textLabel.font = [UIFont systemFontOfSize:15];
	cell.textLabel.textColor = TEXT_COLOR_181818;
	if(indexPath.row == 1)
	{
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOUploadImageView *uploadImgView = (HOUploadImageView *)[cell viewWithTag:114];
		if(uploadImgView == nil)
		{
			[cell.contentView addSubview:self.uploadImgView];
			uploadImgView.tag = 114;
			
			self.uploadImgView.frame = CGRectMake(0,
												  5,
												  self.view.frame.size.width,
												  self.singleImgWidth);
		}
	}
	else if(indexPath.row == 0)
	{
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HORecordView *view = (HORecordView *)[cell viewWithTag:116];
		if(view == nil)
		{
			[cell.contentView addSubview:self.recordView];
			self.recordView.tag = 116;
		}
		
//		UIButton *checkBtn = (UIButton *)[cell viewWithTag:216];
//		if(checkBtn == nil)
//		{
//			checkBtn = [[[UIButton alloc]
//						 initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
//												  128 + 22 + (50 - 24) / 2,
//												  24,
//												  24)] autorelease];
//			checkBtn.tag = 216;
//			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_kuang"] forState:UIControlStateNormal];
//			[checkBtn addTarget:self action:@selector(didClickCheckBtn:) forControlEvents:UIControlEventTouchUpInside];
//			[cell.contentView addSubview:checkBtn];
//		}
//		if(self.isNeedRerepair)
//		{
//			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_gou"] forState:UIControlStateNormal];
//		}
//		else
//		{
//			[checkBtn setBackgroundImage:[UIImage imageNamed:@"IC_putongbaoxiu_kuang"] forState:UIControlStateNormal];
//		}
//		
//		checkBtn.enabled = [self isEnableCheckButton];
//		
//		UILabel *lbl = (UILabel *)[cell viewWithTag:117];
//		if(!lbl)
//		{
//			lbl = [[UILabel alloc] init];
//			lbl.frame = CGRectMake(checkBtn.frame.size.width + checkBtn.frame.origin.x + HO_HORIZONAL_PADDING,
//								   128 + 22 + (50 - 22) / 2,
//								   100,
//								   22);
//			lbl.tag = 117;
//			lbl.textColor = TEXT_COLOR_181818;
//			lbl.font = [UIFont systemFontOfSize:15];
//			lbl.text = NSLocalizedString(@"是否返修", @"是否返修");
//			[cell.contentView addSubview:lbl];
//			[lbl release];
//		}
	}
	return cell;
}

- (void)didClickCheckBtn:(id)sender
{
	
}

- (void)showAuidtionView
{
	[hintView hide];
	int duration = MIN(((int)self.totalTime + 1), MAX_RECORDING_TIME);
	audioTotalTimeLbl.text = [NSString stringWithFormat:@"%d''", MAX(0, duration)];
	auditionView.hidden = NO;
	baseTableview.userInteractionEnabled = NO;
	baseTableview.scrollEnabled = NO;
}

- (void)hideAuditionView
{
	auditionView.hidden = YES;
	baseTableview.scrollEnabled = YES;
	baseTableview.userInteractionEnabled = YES;
}

- (void)recordUIDidHide
{
	baseTableview.scrollEnabled = YES;
	baseTableview.userInteractionEnabled = YES;
}

-(void)initAuditionView
{
	CGRect rect = [UIScreen mainScreen].bounds;
	auditionView = [[UIView alloc]initWithFrame:CGRectMake(30, 130, 216, 160)];
	auditionView.center = CGPointMake(rect.size.width/2, rect.size.height/2-80);
	[auditionView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_record"]]];
	//    view.backgroundColor=[UIColor blackColor];
	auditionView.hidden = YES;
	auditionView.layer.cornerRadius = 10; //圆角背景
	[self.view addSubview:auditionView];
	
	UIButton *playBtn = [[UIButton alloc] initWithFrame:CGRectMake(68, 20, 79, 79)];
	[playBtn setBackgroundImage:[UIImage imageNamed:@"bg_record_content"] forState:UIControlStateNormal];
	[playBtn addTarget:self action:@selector(playAudio:) forControlEvents:UIControlEventTouchUpInside];
	[auditionView addSubview:playBtn];
	[playBtn release];
	
	bgRecordImg = [[UIImageView alloc] initWithFrame:CGRectMake(68, 20, 79, 79)];
	bgRecordImg.image = [UIImage imageNamed:@"playR"];
	[auditionView addSubview:bgRecordImg];
	
	audioTotalTimeLbl = [[UILabel alloc] initWithFrame:CGRectMake(playBtn.frame.size.width + playBtn.frame.origin.x + HO_HORIZONAL_PADDING,
																  (playBtn.frame.size.height - 22) / 2 + playBtn.frame.origin.y,
																  50,
																  22)];
	audioTotalTimeLbl.font = [UIFont systemFontOfSize:13];
	audioTotalTimeLbl.textColor = [UIColor whiteColor];
	[auditionView addSubview:audioTotalTimeLbl];
	
	UIButton *sendAudioBtn = [[UIButton alloc] initWithFrame:CGRectMake(11, 105, 92, 45)];
	[sendAudioBtn addTarget:self action:@selector(saveRecord:) forControlEvents:UIControlEventTouchUpInside];
	[sendAudioBtn setTitle:NSLocalizedString(@"确定", @"确定") forState:UIControlStateNormal];
	[sendAudioBtn setBackgroundImage:[UIImage imageNamed:@"cancleBtn"] forState:UIControlStateNormal];
	[auditionView addSubview:sendAudioBtn];
	[sendAudioBtn release];
	
	UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(113, 105, 92, 45)];
	[closeBtn addTarget:self action:@selector(cancelRecord:) forControlEvents:UIControlEventTouchUpInside];
	[closeBtn setTitle:NSLocalizedString(@"取消", @"取消") forState:UIControlStateNormal];
	[closeBtn setBackgroundImage:[UIImage imageNamed:@"cancleBtn"] forState:UIControlStateNormal];
	[auditionView addSubview:closeBtn];
	[closeBtn release];
	
}

- (CGFloat)getPhotoAndRecordViewHeight
{
	CGFloat height = self.singleImgWidth + [self getDescEditViewHeight] + HO_HORIZONAL_PADDING;
	return height;
}

- (CGFloat)getDescEditViewHeight
{
	return 0;
}

- (CGFloat)getPhotoViewHeight
{
	CGFloat height = self.singleImgWidth + HO_HORIZONAL_PADDING;
	return height;
}

- (void)handleTimer
{
	[self updateAudioIndicate];
}

- (void)updateAudioIndicateWithPlayWithStatus:(AUDIO_PLAY_STATUS)playStatus
{
	
	if(playStatus == AUDIO_PLAYING && auditionStatus != AUDIO_PLAYING)
	{
		[self startTimer];
	}
	
	auditionStatus = playStatus;
	if(playStatus != AUDIO_PLAYING)
	{
		[self invalidateTimer];
	}
}
- (void)startTimer
{
	if(self.auditionTimer == nil)
	{
		self.auditionTimer = [NSTimer scheduledTimerWithTimeInterval: .3
															  target: self
															selector: @selector(handleTimer)
															userInfo: nil
															 repeats: YES];
		
	}
}


- (void)invalidateTimer
{
	if(self.auditionTimer)
	{
		[self.auditionTimer invalidate];
		self.auditionTimer = nil;
	}
	[self updateAudioIndicate];
}

- (void)updateAudioIndicate
{
	
	NSArray *indicateImgArray = [[HODefaultImage getInstance] getPrelistenImgArr];
	
	if(auditionStatus == AUDIO_PLAYING)
	{
		[bgRecordImg setImage:[indicateImgArray objectAtIndex:indicateImgIndex]];
		
		
		indicateImgIndex ++;
		if(indicateImgIndex > ([indicateImgArray count] - 1))
		{
			indicateImgIndex = 0;
		}
	}
	else if(auditionStatus == AUDIO_STOPED)
	{
		indicateImgIndex = 0;
		[bgRecordImg setImage:[UIImage imageNamed:@"playR"]];
	}
	else
	{
		indicateImgIndex = 0;
		[bgRecordImg setImage:[indicateImgArray objectAtIndex:indicateImgIndex]];
	}
	[bgRecordImg setNeedsDisplay];
}

-(void)playAudio:(id)sender
{
	[self.recordView playAudio];
}

- (void)saveRecord:(id)sender
{
	[self hideAuditionView];
	[self.recordView setAudioWithTotalTime:self.totalTime withFileName:self.voiceFileName];
	[baseTableview reloadData];
}

- (void)cancelRecord:(id)sender
{
	[self hideAuditionView];
	[self cleanupAudio];
}

- (void)cleanupAudio
{
	if(self.voiceFileName)
	{
		[HOUtils deleteAudioFromLocal:self.voiceFileName withFileType:FILE_TYPE_AMR];
		[HOUtils deleteAudioFromLocal:self.voiceFileName withFileType:FILE_TYPE_WAV];
	}
	[self.recordView removeAudio];
	self.voiceFileName = nil;
	self.totalTime = 0;
}


#pragma mark
- (void)didConvertSuccess
{
	
}

- (void)downloadVoice
{
	//		self.voiceFileURL = @"http://116.255.168.232:8088/Uploads/Voice/2016-07-04/1110d5a181ed17b0b4fe454ce1de8692.amr";//ios record
	//	self.voiceFileURL = @"http://116.255.168.232:8088/Uploads/Voice/2016-07-06/8d261d617b128a86b38d634068464995.amr";//android record
	//	self.totalTime = 5;
	//	NSLog(@"self.voiceFileURL:%@", self.voiceFileURL);
	
	[self.recordView cleanup];
	if([HOUtils getValideString:self.voiceFileURL].length > 0 && self.totalTime > 0)
	{
		[self.recordView showLoadingWithTotalTime:self.totalTime];
		[[HOVoiceDownloader sharedInstance] downloadFielWithURL:self.voiceFileURL];
	}
}


- (NSString *)getSelectedImages
{
	NSMutableString *imagesStr = [NSMutableString string];
	for(int i = 0; i < [self.uploadImgView getImages].count; i ++)
	{
		UIImage *image = [[self.uploadImgView getImages] objectAtIndex:i];
		NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
		NSString *fileStr = [GTMBase64 stringByEncodingData:imageData];
		if(i > 0)
		{
			[imagesStr appendFormat:@",%@", fileStr];
		}
		else
		{
			[imagesStr appendFormat:@"%@", fileStr];
		}
	}
	return imagesStr;
}

- (NSDictionary *)getMediaDic
{
	NSMutableDictionary *dic = [NSMutableDictionary dictionary];
	[dic setObject:[NSNumber numberWithInt:self.isNeedRerepair] forKey:kHO_FIELD_isReSubmit];
	NSString *imagesStr = [self getSelectedImages];
	[dic setObject:imagesStr forKey:kHO_FIELD_FaultImage];
	if(self.convertedVoiceData != nil)
	{
		NSString *voiceStr = [GTMBase64 stringByEncodingData:self.convertedVoiceData];
		if(voiceStr)
		{
			[dic setObject:voiceStr forKey:kHO_FIELD_FaultVoice];
			[dic setObject:[NSNumber numberWithInt:((int) self.totalTime)] forKey:kHO_FIELD_FaultVoiceTime];
		}
	}
	return dic;
}

- (BOOL)isEnableCheckButton
{
	//是否返修按钮是否可以点击
	return YES;
}


- (BOOL)convertingVoice
{
	if(self.voiceFileName == nil)
	{
		//		[self popupHintView:NSLocalizedString(@"语音录制失败，请重新录制！", @"语音录制失败，请重新录制！")];
		[self submit];
		return NO;
	}
	[self showLoadingView:YES];
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
		[self getConvertedVoiceData];
		dispatch_async(dispatch_get_main_queue(), ^{
			[self submit];
		});
	});
	return YES;
}

- (void)submit
{
	
}

#pragma mark - -- voice


- (void)getConvertedVoiceData
{
	NSString *targetPath =  [HOUtils getFilePathWithFileName:self.voiceFileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:FILE_TYPE_AMR];
	NSString *localPath = [HOUtils getFilePathWithFileName:self.voiceFileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:FILE_TYPE_WAV];
	
	BOOL result = [VoiceConverter wavToAmr:localPath amrSavePath:targetPath];
	if(result)
	{
		self.convertedVoiceData = [NSData dataWithContentsOfFile:targetPath];
		//		[HOUtils deleteAudioFromLocal:self.voiceFileName withFileType:FILE_TYPE_AMR];
		//		[HOUtils deleteAudioFromLocal:self.voiceFileName withFileType:FILE_TYPE_WAV];
	}
}

-(void)submitVoiceWithFileName:(NSString *)fileName withTotalTime:(double)totalTime
{
	//	if(totalTime > 3)
	//	{
	//		[self popupHintView:NSLocalizedString(@"录音时间不能超过60秒，请重新录制", @"录音时间不能超过60秒，请重新录制")];
	//		return;
	//	}
	self.voiceFileName = fileName;
	self.totalTime = totalTime;
	[self.recordView testAudio:self.totalTime withFileName:self.voiceFileName];
	[self showAuidtionView];
}

- (void)takePhoto:(id)sender
{
	[self.takePhotoMgr takePhoto:sender];
}

- (void)viewFullImage:(NSArray *)images withCurrentIndex:(int)index
{
	HOBigImageViewController *viewCtrl = [[HOBigImageViewController alloc] init];
	viewCtrl.imagesData = images;
	viewCtrl.currentIndex = index;
	//	[self.navigationController pushViewController:viewCtrl animated:YES];
	[self.navigationController presentViewController:viewCtrl animated:YES completion:nil];
	[viewCtrl release];
	
	//	[self.navigationController pushViewController:viewCtrl animated:YES];
}

- (void)didPickImages:(NSArray *)images
{
	[self.uploadImgView addImage:images];
}

- (NSInteger)getRemainPhotoCount
{
	return [self.uploadImgView getRemainPhotoCount];
}

- (void)cleanup
{
	self.convertedVoiceData = nil;
	self.voiceFileName = nil;
	[self.uploadImgView cleanup];
	self.isNeedRerepair = NO;
	[self.recordView cleanup];
	[super cleanup];
}

- (void)dealloc
{
	
	[audioTotalTimeLbl release];
	self.uploadImgView = nil;

	self.recordActiveView.delegate = nil;
	self.recordActiveView = nil;
	self.recordView.delegate = nil;
	self.recordView = nil;
	[bgRecordImg release];
	[auditionView release];
	self.convertedVoiceData = nil;
	self.takePhotoMgr.delegate = nil;
	self.takePhotoMgr = nil;
	self.uploadImgView = nil;
	[super dealloc];
}
@end
